package com.mall507.fivepeaks.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class FileUtils {
	public static File createFileInSDCard(String dirPath, String name)
			throws Exception {
		File file = new File(dirPath, name);
		file.createNewFile();
		return file;
	}
	
	public static File createFileInSDCard(String name)
	throws Exception {
		int index = name.lastIndexOf(File.separator);
		String dir = name.substring(0, index);
		creatSDDir(dir);
		return createFileInSDCard(dir, name.substring(index+1));
	}
	
	public static File creatSDDir(String dirPath) {
		File dirFile = new File(dirPath);
		if(!dirFile.exists()) dirFile.mkdirs();
		return dirFile;
	}
	
	public static boolean isFileExist(String name) {
		return new File(name).exists();
	}
	
	public static File write2SDFromInput(String name, InputStream input) {
		if(input == null) return null;
		File file = null;
		try {   
			file = createFileInSDCard(name);
			FileOutputStream output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			int temp = -1;
			while ((temp = input.read(buffer)) != -1) {
				output.write(buffer, 0, temp);
			}
			output.flush();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return file;
	}
	
	public static void deleteFile(String path){
		if(path == null || "".equals(path))return;
		File file = new File(path);
		if(file.exists()){
			file.delete();
		}
	}

	public static void deleteFile(File file) {
		if (file == null || !file.exists())return;
			file.delete();
	}
	public static void deleteAllFiles(File root) {
		File files[] = root.listFiles();
		if (files != null)
			for (File f : files) {
				if (f.isDirectory()) { 
					deleteAllFiles(f);
					try {
						f.delete();
					} catch (Exception e) {
					}
				} else {
					if (f.exists()) { 
						deleteAllFiles(f);
						try {
							f.delete();
						} catch (Exception e) {
						}
					}
				}
			}
	}
}
